package com.ibeeking.gmc.global.g.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.entity.GlobalVariableDTO;
import com.ibeeking.found.common.entity.GlobalVariableParam;
import com.ibeeking.found.common.entity.VariableQuery;
import com.ibeeking.gmc.global.g.rest.service.IGlobalVariableService;
import com.ibeeking.gmc.global.service.common.dos.GlobalVariableDO;
import com.ibeeking.gmc.global.service.mapper.GlobalVariableMapper;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.id.IdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class GlobalVariableServiceImpl extends ServiceImpl<GlobalVariableMapper, GlobalVariableDO> implements IGlobalVariableService {
    @Resource
    private GlobalVariableMapper GlobalVariableMapper;

    /**
     * 修改
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addAndModify(GlobalVariableParam param){
        String paramName = param.getPkey();
        GlobalVariableDO variableDO = this.GlobalVariableMapper.selectOne(new LambdaQueryWrapper<GlobalVariableDO>()
                .eq(GlobalVariableDO::getPkey, paramName));
        if(variableDO != null){
            variableDO.setPvalue(param.getPvalue());
            return this.GlobalVariableMapper.updateById(variableDO) > 0;
        }else{
            variableDO = BeanUtil.convertBean(param, GlobalVariableDO.class);
            variableDO.setId(IdGenerator.getId());
            return this.GlobalVariableMapper.insert(variableDO) >0;
        }
    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public GlobalVariableDTO queryById(Long id) {
        GlobalVariableDO variableDO = this.GlobalVariableMapper.selectById(id);
        GlobalVariableDTO GlobalVariableVO = BeanUtil.convertBean(variableDO, GlobalVariableDTO.class);
        return GlobalVariableVO;
    }

    /**
     * @param query
     * @return
     */
    @Override
    public GlobalVariableDTO queryGlobalVariable(VariableQuery query){
        GlobalVariableDO variableDO = this.GlobalVariableMapper.selectOne(new LambdaQueryWrapper<GlobalVariableDO>()
                .eq(StringUtils.isNotEmpty(query.getPkey()), GlobalVariableDO::getPkey, query.getPkey())
                .eq(StringUtils.isNotEmpty(query.getPvalue()), GlobalVariableDO::getPvalue, query.getPvalue()));
        if(variableDO!=null)
            return BeanUtil.convertBean(variableDO,GlobalVariableDTO.class) ;
        return null;
    }

}
